import 'dart:convert';
import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:dio/dio.dart';
import 'Util.dart';
import 'card.dart';

class MyHome2Page extends StatefulWidget {
  MyHome2Page({Key key, this.title, this.para}) : super(key: key);
  final String title;
  final Map<String, dynamic> para;
  @override
  _MyHomePageState2 createState() => _MyHomePageState2();
}

class _MyHomePageState2 extends State<MyHome2Page> {
  Map<String, dynamic> buildings = {};
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    print(this.widget.para);
  }
  /// 实际上的真正跳转
  realPush(qr) {

    String block_key = widget.para["block_key"];
    Map<String,String> dic = {"api_key":"xQITe6bZFUrmeJbkcKgkUzajUI6FGLA","block_key":block_key,"lang":"en","staff_key":qr};
    var dio = Dio();
    if (ShareHandle.instance.proxy.length > 0){
      (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
        client.findProxy = (uri) {
          return ShareHandle.instance.proxy;
        };
      };
    }
    SharedPreferences.getInstance().then((value){
      String domain = value.getString("buildings").toMap()["subdomain"]
          .toString();
      dio.post("${domain}/api/staff/duty",data:FormData.fromMap(dic)).then((value){
        print(value.toString());
        final result = value.toResult();
        if (result.item2 || result.item3 == 210){
          var _dic = this.widget.para;
          _dic["staff_key"] = qr;
          Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => CardPage(
                    title: widget.title, para: _dic)),
          );
        }
      });
    });
  }

  Future scan() async {
    if (ShareHandle.instance.shouldUseCamara){
      var result = await BarcodeScanner.scan();
      if (result.type == ResultType.Barcode) {
        showDialog<Null>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return new AlertDialog(
                title: new Text(result.rawContent),
                //可滑动
                content: new SingleChildScrollView(
                  child: new ListBody(
                    children: <Widget>[
                      new Text(''),
                    ],
                  ),
                ),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text('确定'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      realPush(result.rawContent);
                    },
                  ),
                  new FlatButton(
                    child: new Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            });
      }

      print(result.type); // The result type (barcode, cancelled, failed)
      print(result.rawContent); // The barcode content
      print(result.format); // The barcode format (as enum)
      print(result
          .formatNote); // If a unknown format was scanned this field contains a note
    }else{
      realPush("wgEWKqHbRE3fIMeyHg");
    }
  }
  @override
  Widget build(BuildContext context) {
    SharedPreferences.getInstance().then((value) {
      setState(() {
        buildings = value.getString("buildings").toMap();
      });
    });
    return Scaffold(
      body: Row(
        children: <Widget>[
          Expanded(
            child: Image(
              fit: BoxFit.cover,
              image: AssetImage("assets/images/login_bg02.png"),
            ),
          ),
          Expanded(
              child: Container(
            color: Color.fromARGB(255, 58, 58, 58),
            child: Stack(
              children: <Widget>[
                Align(
                  child: Text(
                    "V 1.0",
                    style: TextStyle(color: Colors.white),
                  ),
                  alignment: Alignment.bottomCenter,
                ),
                Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Image(
                        image:
                            AssetImage("assets/images/standby_icon_staff.png"),
                      ),
                      SizedBox(height: 20),
                      FlatButton(
                        onPressed: scan,
                        child: Stack(
                          alignment: Alignment.center,
                          children: <Widget>[
                            Image(
                              image: AssetImage(
                                  "assets/images/btn_bg_scan-_qr.png"),
                            ),
                            Text(
                              "掃描工作證",
                              style: new TextStyle(
                                  color: Color.fromARGB(255, 255, 255, 255),
                                  fontSize: 18),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                )
              ],
            ),
          )),
        ],
      ),
    );
  }
}
